//
//  FSBootViewController.m
//  FSiOSClient
//
//  Created by purlible on 2024/8/27.
//

#import "FSBootViewController.h"
#import "FSPrivacyAlertViewController.h"
#import "AppDelegate.h"
#import "FSHomeViewController.h"

@interface FSBootViewController () <FSPrivacyAlertViewDelegate>

@end

@implementation FSBootViewController

- (void)launchScreenView {
    
    NSString *UILaunchStoryboardName = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchStoryboardName"];
     if(UILaunchStoryboardName == nil){
         NSLog(@"从 LaunchScreen 中获取启动图失败!");
     }
     UIViewController *LaunchScreenSb = [[UIStoryboard storyboardWithName:UILaunchStoryboardName bundle:nil] instantiateInitialViewController];
     if(LaunchScreenSb){
         UIView * view = LaunchScreenSb.view;
         // 加入到UIWindow后，LaunchScreenSb.view的safeAreaInsets在刘海屏机型才正常。
         UIWindow *containerWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
         view.frame = containerWindow.bounds;
         [containerWindow addSubview:view];
         [containerWindow layoutIfNeeded];
         UIImage *image = [self imageFromView:view];
         containerWindow = nil;
         
         UIImageView *launchImageView = [[UIImageView alloc] initWithImage:image];
         [self.view addSubview:launchImageView];
         [launchImageView mas_makeConstraints:^(MASConstraintMaker *make) {
             make.edges.equalTo(self.view);
         }];
     }
}

- (UIImage*)imageFromView:(UIView*)view
{
    if(CGRectIsEmpty(view.frame)) return nil;
    CGSize size = view.bounds.size;
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self launchScreenView];
    
    if ([FSPrivacyAlertViewController isAgreed])
    {
        
        [self forwardApp];
    }
    else
    {
        [FSPrivacyAlertViewController tryShowPrivacyAlertWithController:self delegate:self];
    }
}

- (void)privacyAlertViewDidAgreed:(BOOL)isAgree
{
    if (isAgree)
    {
        NSString *currentVersion =  [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
        
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
        [userDefault setObject:currentVersion forKey:kHCBootPrivacyAgreed];
        [userDefault synchronize];
        
        [self forwardApp];
    }
    else
    {
        exit(0);
    }
}

- (void)forwardApp
{
    FSHomeViewController *vc = [[FSHomeViewController alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];

    UIWindow* window = ((AppDelegate *)[UIApplication sharedApplication].delegate).window;

    [window setRootViewController:nav];
    [window makeKeyAndVisible];
}



@end
